package com.csun.nusing.ui.familyactivity;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.csun.nusing.R;
import com.csun.nusing.bean.UrlBean;
import com.csun.nusing.bean.jsonbean.BedTimeJsonBean;
import com.csun.nusing.bean.jsonbean.BedTimeJsonBean.BedTimeDataBean;
import com.csun.nusing.bean.jsonbean.DeviceWatchJsonBean;
import com.csun.nusing.bean.jsonbean.DeviceWatchJsonBean.DeviceWatchDataBean;
import com.csun.nusing.bean.jsonbean.SearchOlderInfoJsonBean;
import com.csun.nusing.bean.jsonbean.SelectPhoneAlarmDetailJsonBean;
import com.csun.nusing.bean.jsonbean.SelectPhoneAlarmDetailJsonBean.SelectPhoneAlarmDetailDataBean;
import com.csun.nusing.presenter.OldrestDetailsPresenter;
import com.csun.nusing.presenter.inter.IBase;
import com.csun.nusing.ui.BaseActivity;
import com.csun.nusing.ui.activity.SuiFangDeviceActivity;
import com.csun.nusing.ui.myview.RoundImageView;
import com.csun.nusing.util.L;
import com.csun.nusing.util.SPUtils;
import com.csun.nusing.util.ToastUtil;
import com.google.gson.Gson;
import com.home.administrator.okhttplibrary.IOkTaskCallback;
import com.home.administrator.okhttplibrary.OkHttpTask;
import com.home.administrator.okhttplibrary.OkHttpTask.OkHttpTaskBuidler.OkType;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;

/**
 * 老人详情界面 ClassName: OldrestDetailsActivity
 *
 * @author fzq
 * @Description: TODO
 * @date 2017-10-23
 */
public class FamilyOldrestDetailsActivity extends
        BaseActivity<OldrestDetailsPresenter> implements IBase {

    private View suifangview;// 随访仪
    private View alarmview;// 报警器
    private View watchview;// 手表
    private View sleepview;// 床垫
    private String olderId;
    private String olderName;
    private RoundImageView headiv;
    private TextView nametv;
    private TextView sexagetv;
    private TextView birtv;
    private TextView chuanghaotv;
    private TextView egnametv;
    private TextView egcodetv;
    private String olderPhotopath;
    private String olderBir;
    private String olderSex;
    private String olderEcgname;
    private String olderEcgPhone;
    private int biryear;
    private int oldAge;
    private String birday;
    private String birmon;
    private LinearLayout suifangll;
    private LinearLayout alarmll;
    private LinearLayout watchll;
    private RelativeLayout sleepll;
    private TextView sleepCodetv;
    private TextView xintiaotv;
    private TextView zaichaungstatetv;
    private TextView huxitv;
    private TextView xintiaobaojintv;
    private TextView fanshenbaojintv;
    private String authorization;
    private OkHttpClient client;
    private TextView watchcodetv;
    private TextView watchactiontv;
    private TextView watchxintiaotv;
    private TextView watchxueyatv;
    private TextView watchplacetv;
    private TextView alarmcodetv;
    private TextView alarmstatetv;
    private TextView alarmxinhaotv;
    private TextView alarmdiancitv;
    private TextView alarmdianyatv;
    protected DeviceWatchJsonBean nursingdevicewatchbean;
    private TextView alarmplace;
    protected SelectPhoneAlarmDetailJsonBean nursingdevicealarmbean;
    private String olderage;
    private String roombed;
    private ScheduledExecutorService scheduledExecutorService;
    private BedTimeJsonBean bedtimebean;
    private String roomId;
    public static final MediaType JSON = MediaType
            .parse("application/json; charset=utf-8");
    private ImageView editiv;
    private RelativeLayout nobedrl;
    private TextView nobedtv;
    private LinearLayout havebedll;
    private String bedNo;

    @Override
    public int getContentViewId() {
        return R.layout.activity_family_oldrestdetails;
    }

    @Override
    public void initSubViews(View view) {
        super.initSubViews(view);
        findView();
        controlView();
    }

    /**
     * 初始控件
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-10-23
     */
    private void findView() {
        editiv = findViewById(R.id.older_detail_edit_iv);
        suifangview = findViewById(R.id.family_oldrest_details_suifang_view);
        alarmview = findViewById(R.id.family_oldrest_details_alarm_view);
        watchview = findViewById(R.id.family_oldrest_details_watch_view);
        sleepview = findViewById(R.id.family_oldrest_details_sleep_view);
        suifangll = findViewById(R.id.family_oldrest_details_suifang_ll);
        alarmll = findViewById(R.id.family_oldrest_details_alarm_ll);
        watchll = findViewById(R.id.family_oldrest_details_watch_ll);
        sleepll = findViewById(R.id.family_oldrest_details_sleep_rl);

        headiv = findViewById(R.id.family_olderdetail_oldhead_riv);
        nametv = findViewById(R.id.family_olderdetail_oldername_tv);
        sexagetv = findViewById(R.id.family_olderdetail_detail_sexage_tv);
        birtv = findViewById(R.id.family_olderdetail_detail_bir_tv);
        chuanghaotv = findViewById(R.id.family_olderdetail_detail_chuanghao_tv);
        egnametv = findViewById(R.id.family_olderdetail_detail_egname_tv);
        egcodetv = findViewById(R.id.family_olderdetail_detail_egcode_tv);

        // 床垫
        sleepCodetv = findViewById(R.id.family_olderdetail_chuangdian_code_tv);
        zaichaungstatetv = findViewById(R.id.family_olderdetail_chuangdian_zaichaung_state_tv);
        xintiaotv = findViewById(R.id.family_olderdetail_chuangdian_xintiao_state_tv);
        huxitv = findViewById(R.id.family_olderdetail_chuangdian_huxi_state_tv);
        xintiaobaojintv = findViewById(R.id.family_olderdetail_chuangdian_huxibaojin_state_tv);
        fanshenbaojintv = findViewById(R.id.family_olderdetail_chuangdian_fanshenbaojin_state_tv);
        havebedll = findViewById(R.id.family_oldrest_have_sleep_ll);
        nobedrl = findViewById(R.id.family_olderer_detail_no_bed_rl);
        nobedtv = findViewById(R.id.family_olderer_detail_no_bed_tv);
        // end

        /**
         * 手表
         */
        watchcodetv = findViewById(R.id.family_olderdetail_watch_code_tv);
        watchactiontv = findViewById(R.id.family_olderdetail_watch_action_state_tv);
        watchxintiaotv = findViewById(R.id.family_olderdetail_watch_xintiao_state_tv);
        watchxueyatv = findViewById(R.id.family_olderdetail_watch_xueya_state_tv);
        watchplacetv = findViewById(R.id.family_olderdetail_watch_place_state_tv);

        /**
         * 报警器
         */
        alarmcodetv = findViewById(R.id.family_olderdetail_alarm_code_tv);
        alarmstatetv = findViewById(R.id.family_olderdetail_alarm_state_tv);
        alarmplace = findViewById(R.id.family_olderdetail_alarm_place_tv);
        alarmxinhaotv = findViewById(R.id.family_olderdetail_alarm_xinhao_state_tv);
        alarmdiancitv = findViewById(R.id.family_olderdetail_alarm_dianci_state_tv);
        alarmdianyatv = findViewById(R.id.family_olderdetail_alarm_dianya_state_tv);

    }

    /**
     * 点击事件
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-10-24
     */
    private void controlView() {
        suifangview.setOnClickListener(new click());
        alarmview.setOnClickListener(new click());
        watchview.setOnClickListener(new click());
        sleepview.setOnClickListener(new click());
        editiv.setOnClickListener(new click());
        nobedtv.setOnClickListener(new click());
    }

    @Override
    public void initData() {
        super.initData();
        olderId = getIntent().getStringExtra("olderId");
        olderName = getIntent().getStringExtra("olderName");
        roomId = getIntent().getStringExtra("roomId");
        olderPhotopath = getIntent().getStringExtra("olderPhotopath");
        Glide.with(this).load("" + olderPhotopath).into(headiv);
        nametv.setText("" + olderName);
        olderBir = getIntent().getStringExtra("olderBir");
        olderSex = getIntent().getStringExtra("olderSex");
        olderage = getIntent().getStringExtra("olderage");
        olderEcgname = getIntent().getStringExtra("olderEcgname");
        olderEcgPhone = getIntent().getStringExtra("olderEcgPhone");
        roombed = getIntent().getStringExtra("roombed");
        authorization = (String) SPUtils.get(this, "authorization", "");
        L.e("fzq", "olderinfo--:" + olderSex + "   " + olderage + "  " + roombed + "  " + olderBir);
        if (olderBir != null && olderBir.length() > 7) {
            // biryear = Integer.parseInt(olderBir.substring(0, 4));
            // Calendar cal = Calendar.getInstance();
            // int year = cal.get(Calendar.YEAR);
            // oldAge = year - biryear;
            if (olderSex.equals("0")) {
                sexagetv.setText(getString(R.string.sex_man_age) + olderage + getString(R.string.age));
            } else {
                sexagetv.setText(getString(R.string.sex_woman_age) + olderage + getString(R.string.age));
            }
            // 1914-05-22
            String[] ss = olderBir.split("-");
            birmon = ss[1];
            birday = ss[2];
            birtv.setText(getString(R.string.birthday_s) + birmon + getString(R.string.month) + birday + getString(R.string.day));
        }
        egnametv.setText(getString(R.string.urgent_name_s) + olderEcgname);
        egcodetv.setText(getString(R.string.urgent_phone_s) + olderEcgPhone);
        chuanghaotv.setText(getString(R.string.room_bed_s) + roombed);
        bedNo = getIntent().getStringExtra("bedNo");
        L.e("fzq", "bedNo--: "+bedNo);
        if (bedNo==null || bedNo.equals("null")){
            //无床位
            nobedrl.setVisibility(View.VISIBLE);
            havebedll.setVisibility(View.GONE);
        }
        requsetsleepData();
        requsetwatchData();
        requsetalarmData();
        //定时请求数据
        scheduledExecutorService = Executors.newScheduledThreadPool(1);
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                requsetsleepData();
                requsetwatchData();
                requsetalarmData();
            }
        }, 60, 60, TimeUnit.SECONDS);
    }

    /**
     * 报警器
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-11-3
     */
    private void requsetalarmData() {
        if (roomId == null || roomId.equals("null")) {
            return;
        }
        Map<String, String> param = new HashMap<String, String>();
        param.put("roomId", "" + roomId);
        OkHttpTask.newInstance(this).post(param, OkType.form)
                .addHeader("authorization", authorization)
                .enqueue(new IOkTaskCallback() {
                    @Override
                    public void onSuccess(String result) {
                        if (result != null) {
                            Log.e("fzq", "-------" + result);
                            Gson gson = new Gson();
                            nursingdevicealarmbean = gson.fromJson(result,
                                    SelectPhoneAlarmDetailJsonBean.class);
                            if (nursingdevicealarmbean != null) {
                                if (nursingdevicealarmbean.getData() != null) {
                                    controlAlarmList(nursingdevicealarmbean
                                            .getData());
                                }
                            }
                        }
                    }
                }).start(UrlBean.SELECTPHONEDATEBYROOMURL);

    }

    /**
     * 报警器数据处理
     *
     * @param @param data
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-11-3
     */
    protected void controlAlarmList(List<SelectPhoneAlarmDetailDataBean> list) {
        if (list != null
                && list.size() != 0) {
            alarmcodetv.setText("" + list.get(0).getDeviceNo());
            // alarmstatetv.setText("");
            if (list.get(0).getStatus() == -1) {
                alarmstatetv.setText(R.string.dropped);
            } else if (list.get(0).getStatus() == 0) {
                alarmstatetv.setText(R.string.deploy_troops_for_defence);
            } else if (list.get(0).getStatus() == 1) {
                alarmstatetv.setText(R.string.disarm);
            }
            alarmplace.setText("" + list.get(0).getRoomId());
            alarmdianyatv.setText("" + list.get(0).getSvtg());
            alarmdiancitv.setText("" + list.get(0).getOvtg());
            alarmxinhaotv.setText("" + list.get(0).getSignal());
        }
    }

    private void requsetwatchData() {
        Map<String, String> param = new HashMap<String, String>();
        param.put("id", "" + olderId);
        OkHttpTask.newInstance(this).post(param, OkType.form)
                .addHeader("authorization", authorization)
                .enqueue(new IOkTaskCallback() {
                    @Override
                    public void onSuccess(String result) {
                        if (result != null) {
                            Log.e("fzq", "-------" + result);
                            Gson gson = new Gson();
                            nursingdevicewatchbean = gson.fromJson(result,
                                    DeviceWatchJsonBean.class);
                            if (nursingdevicewatchbean != null) {
                                if (nursingdevicewatchbean.getData() != null) {
                                    controlWatchList(nursingdevicewatchbean
                                            .getData());
                                }
                            }
                        }
                    }
                }).start(UrlBean.WATCHDEVICEURL);

    }

    /**
     * 显示手表
     *
     * @param @param list
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-11-3
     */
    protected void controlWatchList(DeviceWatchDataBean deviceWatchDataBean) {
        if (deviceWatchDataBean.getRealtime() != null) {
            watchcodetv.setText(R.string.it_watch);
            watchactiontv.setText(R.string.action);
            watchxintiaotv.setText(""
                    + deviceWatchDataBean.getRealtime().getHeartrate());
            watchxueyatv.setText(deviceWatchDataBean.getRealtime().getDbp()
                    + "/" + deviceWatchDataBean.getRealtime().getSbp());
            watchplacetv.setText(""
                    + deviceWatchDataBean.getRealtime().getLocation());

        }
    }

    /**
     * 加载床垫数据
     *
     * @param
     * @return void
     * @throws
     * @Description: TODO
     * @author fzq
     * @date 2017-11-3
     */
    private void requsetsleepData() {
        Map<String, String> param = new HashMap<String, String>();
        Log.e("fzq", "---------olderId-" + olderId);
        param.put("id", "" + olderId);
        OkHttpTask.newInstance(this).post(param, OkType.form)
                .addHeader("authorization", authorization)
                .enqueue(new IOkTaskCallback() {
                    @Override
                    public void onSuccess(String result) {
                        if (result != null) {
                            Log.e("fzq", "-------" + result);
                            Gson gson = new Gson();
                            bedtimebean = gson.fromJson(result,
                                    BedTimeJsonBean.class);
                            if (bedtimebean != null) {
                                if (bedtimebean.getData() != null) {
                                    controlSleepData(bedtimebean
                                            .getData());
                                }
                            }
                        }
                    }
                }).start(UrlBean.SLEEPREALTIMEYURL);


    }

    protected void controlSleepData(BedTimeDataBean data) {
        sleepCodetv.setText(data.getSleepId());
        if (data.isInBedStatus()) {
            zaichaungstatetv.setText(R.string.in_bed);
        } else {
            zaichaungstatetv.setText(R.string.bed_detail_out_bed_state);
        }
        xintiaotv.setText(data.getHeartbeat() + " ");
        huxitv.setText(data.getBreath() + " ");
        if (data.getAlarm() == 1) {
            xintiaobaojintv.setText(R.string.alarm);
        } else {
            xintiaobaojintv.setText(R.string.bed_detail_none);
        }
        //
        if (data.getAction() == 0) {
            fanshenbaojintv.setText(R.string.alarm);
        } else {
            fanshenbaojintv.setText(R.string.bed_detail_none);
        }
    }


    /**
     * ClassName: click
     *
     * @author fzq
     * @Description: TODO00
     * @date 2017-10-24
     */
    private class click implements OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = null;
            switch (v.getId()) {
                case R.id.family_oldrest_details_suifang_view:
                    setLeanGone();
                    suifangview
                            .setBackgroundResource(R.drawable.laorenxiangqing_shebei_xuanzhong_hg);
                    intent = new Intent(FamilyOldrestDetailsActivity.this,
                            SuiFangDeviceActivity.class);
                    intent.putExtra("olderId", "" + olderId);
                    intent.putExtra("isFamily", true);
                    startActivity(intent);
                    suifangll.setVisibility(View.VISIBLE);
                    break;
                case R.id.family_oldrest_details_alarm_view:
                    setLeanGone();
                    alarmview
                            .setBackgroundResource(R.drawable.laorenxiangqing_shebei_xuanzhong_js);
                    alarmll.setVisibility(View.VISIBLE);
                    break;
                case R.id.family_oldrest_details_watch_view:
                    setLeanGone();
                    watchview
                            .setBackgroundResource(R.drawable.laorenxiangqing_shebei_xuanzhong_js);
                    watchll.setVisibility(View.VISIBLE);
                    break;
                case R.id.family_oldrest_details_sleep_view:
                    setLeanGone();
                    sleepview
                            .setBackgroundResource(R.drawable.laorenxiangqing_shebei_xuanzhong_js);
                    sleepll.setVisibility(View.VISIBLE);
                    break;
                case R.id.older_detail_edit_iv:
                    Intent intents = new Intent(FamilyOldrestDetailsActivity.this, FamilyEditOlderActivity.class);
                    intents.putExtra("olderId", "" + olderId);
                    startActivityForResult(intents, 1);
                    break;
                case R.id.family_olderer_detail_no_bed_tv:
                    Intent intens = new Intent(FamilyOldrestDetailsActivity.this, FamilyBindDeviceListActivity.class);
                    intens.putExtra("olderId", "" + olderId);
                    startActivityForResult(intens, 1);
                    break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //刷新老人信息//
        L.e("fzq","-------onActivityResult");
        authorization = (String) SPUtils.get(this, "authorization", "");
        Map<String, String> param = new HashMap<String, String>();
        param.put("id", olderId + "");
        OkHttpTask.newInstance(this).post(param, OkType.form)
                .addHeader("authorization", authorization)
                .enqueue(new IOkTaskCallback() {
                    @Override
                    public void onSuccess(String result) {
                        if (result != null) {
                            Gson gson = new Gson();
                            SearchOlderInfoJsonBean oldersonBean = gson.fromJson(
                                    result, SearchOlderInfoJsonBean.class);
                            if (oldersonBean.isStatus()) {
                                if (oldersonBean.getData() != null) {
                                    controlData(oldersonBean.getData());
                                }
                            } else {
                                ToastUtil.showMessage(FamilyOldrestDetailsActivity.this, oldersonBean.getMessage());
                            }
                        }
                    }
                }).start(UrlBean.OLDERSHOWURL);
    }

    private void controlData(SearchOlderInfoJsonBean.SearchOlderInfoDataBean data) {
        olderId = ""+data.getId();
        olderName = data.getName();
        olderPhotopath = data.getHeadpicture();
        Glide.with(this).load("" + olderPhotopath).into(headiv);
        nametv.setText("" + olderName);
        olderBir = data.getBirthday();
        olderSex = data.getSex();
        olderage = data.getAge();
        olderEcgname = data.getEgContact();
        olderEcgPhone = data.getEgPhone();
        roombed = data.getBuildingName()+"栋"+data.getRoomNo()+"房"+data.getBedNo()+"床";
        authorization = (String) SPUtils.get(this, "authorization", "");
        Log.e("fzq", "" + olderSex + "   " + olderage + "  " + roombed + "  " + olderBir);
        if (olderBir != null && olderBir.length() > 7) {
            // biryear = Integer.parseInt(olderBir.substring(0, 4));
            // Calendar cal = Calendar.getInstance();
            // int year = cal.get(Calendar.YEAR);
            // oldAge = year - biryear;
            if (olderSex.equals("0")) {
                sexagetv.setText(getString(R.string.sex_man_age) + olderage + getString(R.string.age));
            } else {
                sexagetv.setText(getString(R.string.sex_woman_age) + olderage + getString(R.string.age));
            }
            // 1914-05-22
            String[] ss = olderBir.split("-");
            birmon = ss[1];
            birday = ss[2];
            birtv.setText(getString(R.string.birthday_s) + birmon + getString(R.string.month) + birday + getString(R.string.day));
        }
        egnametv.setText(getString(R.string.urgent_name_s) + olderEcgname);
        egcodetv.setText(getString(R.string.urgent_phone_s) + olderEcgPhone);
        chuanghaotv.setText(getString(R.string.room_bed_s) + roombed);
        if (data!=null&&data.getBedNo()!=null&&data.getBedNo().length()<2){
            //无床位
            nobedrl.setVisibility(View.VISIBLE);
            havebedll.setVisibility(View.GONE);
        }else {
            //无床位
            nobedrl.setVisibility(View.GONE);
            havebedll.setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected OldrestDetailsPresenter getPresenter() {
        return new OldrestDetailsPresenter(this);
    }

    public void setLeanGone() {
        suifangview.setBackgroundResource(R.drawable.kongbai);
        alarmview.setBackgroundResource(R.drawable.kongbai);
        watchview.setBackgroundResource(R.drawable.kongbai);
        sleepview.setBackgroundResource(R.drawable.kongbai);
        sleepll.setVisibility(View.GONE);
        watchll.setVisibility(View.GONE);
        alarmll.setVisibility(View.GONE);
        suifangll.setVisibility(View.GONE);
    }

}
